package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.example.photography.MainActivity;
import com.example.photography.MainActivity2;
import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.bean.UpdateInfo;
import com.example.photography.bean.UserBean;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.util.Util;
import com.example.photography.view.Message_Dialog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

public class WelcomeActivity extends BaseActivity {


    @BindView(R.id.iv_welcome_icon)
    ImageView ivWelcomeIcon;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.tv_welcome_version)
    TextView tvWelcomeVersion;
    @BindView(R.id.ll_text)
    LinearLayout llText;
    @BindView(R.id.rl_welcome)
    RelativeLayout rlWelcome;
    private long startTime;
    private UpdateInfo updateInfo;
    private Message_Dialog mMyDialog;

    @Override
    protected void initData() {
        //提供启动动画
        setAnimation();
        initview();

        //联网检测应用是否为最新版本
        updateApkFile();
    }

    private void initview() {
        tvWelcomeVersion.setText(getVersion());
    }

    private void updateApkFile() {
        //1.判断手机是否可以联网
        final Boolean connect = isConnect();
        if (!connect) {//没有网络
            //获取当前系统时间
            startTime = System.currentTimeMillis();
            Util.show(this, "当前好像没有网络~");
//            toMain();

        } else {//有移动网络
            //联网获取服务器的最新版本数据

            AsyncHttpClient client = new AsyncHttpClient();
            client.get(AppNetConfig.update, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //解析json数据
                    String jsonData = new String(responseBody);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String resultCode = jsonObject.getString("status");
                        if (resultCode.equals("204")) {
                            String data = jsonObject.getString("data");
                            updateInfo = JSON.parseObject(data, UpdateInfo.class);
                            if (updateInfo != null) {//将新版本信息存入数据库
                                Model.getInstance().getUpdateTableDao().addAccount(updateInfo);
                                handler.sendEmptyMessageDelayed(2, 0);
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Toast.makeText(WelcomeActivity.this, "联网请求数据失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void toMain() {
        long currentTime = System.currentTimeMillis();
        long delayTime = 3000 - (currentTime - startTime);
        if (delayTime < 0) {
            delayTime = 0;
        }
        handler.sendEmptyMessageDelayed(1, delayTime);
    }

    //判断是否联网
    private Boolean isConnect() {
        Boolean connect = false;
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            connect = networkInfo.isConnected();
        }
        return connect;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_welcome;
    }

    /**
     * 发送消息
     */
    private void SendMessage() {
        /**测试*/
        SharedPreferences preferences = getSharedPreferences("isLogin", MODE_PRIVATE);
        Constant.UID = preferences.getString("UID", "00");
        /**
         *判断用户是否登录过
         */
        if (!Constant.UID.equals("00")) {//登录过
            //获取到当前登录用户的信息
            UserBean.User user = Model.getInstance().getUerAccountDao().getAccountById_unique(Constant.UID);

            if (user != null) {
                //登录成功后调用的方法
                Model.getInstance().loginSuccess(user);
                goToActivity(MainActivity2.class, new Bundle());

            } else {
                goToActivity(Login_activity.class, new Bundle());
            }
        } else {
            goToActivity(Login_activity.class, new Bundle());
        }
        removeCurrentActivity();
    }

    private void setAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);//0：完全透明 1:完全不透明
        alphaAnimation.setDuration(3000);//保持3秒
        alphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());//设置动画的变化率

        //方式一
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            //当动画结束时：调用如下方法
            @Override
            public void onAnimationEnd(Animation animation) {
                handler.sendEmptyMessageDelayed(1, 0);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //启动动画
        rlWelcome.startAnimation(alphaAnimation);
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    SendMessage();//发送消息
                    break;
                case 2:
                    //获取当前应用的版本信息
                    String version = getVersion();
                    //更新页面版本号
                    //比较服务器获取的最新版本跟本应用的版本是否一致
                    if (version.equals(updateInfo.version)) {
                        toMain();
                    } else {
                        //弹出框
                        View view = getLayoutInflater().inflate(R.layout.message_dialog, null);
                        mMyDialog = new Message_Dialog(WelcomeActivity.this, 0, 0, view, R.style.DialogTheme);
                        TextView message = view.findViewById(R.id.tv_message);
                        TextView title = view.findViewById(R.id.tv_title);
                        TextView confirm = view.findViewById(R.id.btn_confirm);//获取diolog里面的返回键和确定键
                        TextView cancel = view.findViewById(R.id.btn_cancel);
                        title.setText("应用更新");
                        message.setText(updateInfo.desc_apk);
                        confirm.setText("前往更新");
                        cancel.setText("忽略");
                        if (!isFinishing()) {
                            mMyDialog.show();
                        }
                        confirm.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //todo 待使用回调
                                //前往消息activity
                                mMyDialog.dismiss();
                                goToActivityForResult(UpdateActivity.class, 1, new Bundle());
                            }
                        });
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //弹出框消失实现
                                mMyDialog.dismiss();
                                SendMessage();
                            }
                        });
                    }
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    SendMessage();
                    break;
            }
        }
    }

    /**
     * 获取当前版本号
     *
     * @return版本号
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //如果找不到对应的应用包信息，就返回“未知版本”
            e.printStackTrace();
        }
        return version;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除所有的未被执行的消息
        handler.removeCallbacksAndMessages(null);
        if (mMyDialog != null) {
            mMyDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
